import { hasToken } from '@/utils/token'
import { ApiRes, Article, Channel } from '@/types/data'
import request from '@/utils/request'
import { RootThunkAction } from '@/types/store'
import { getChannels, setChannels } from '@/utils/storage'

// 获取我的频道
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 1.登录时，直接从服务器上获取
    if (hasToken()) {
      const res = await request.get<ApiRes<{ channels: Channel[] }>>(
        '/user/channels'
      )

      const channels = res.data.data.channels
      dispatch({
        type: 'home/set_user_channels',
        payload: channels
      })
    } else {
      const channels = getChannels()

      // 2.1如果本地有数据，则用本地
      if (channels.length > 0) {
        dispatch({
          type: 'home/set_user_channels',
          payload: channels
        })
      }
      // 2.2如果本地没数据，则先从服务器取，再存入本地
      else {
        const res = await request.get<ApiRes<{ channels: Channel[] }>>(
          '/user/channels'
        )

        const channels = res.data.data.channels
        dispatch({
          type: 'home/set_user_channels',
          payload: channels
        })

        setChannels(channels)
      }
    }
  }
}

// 获得所有频道
export function getALlChannel(): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiRes<{ channels: Channel[] }>>('/channels')

    const { channels } = res.data.data

    dispatch({
      type: 'home/set_all_channels',
      payload: channels
    })
  }
}

// 设置激活频道
export function setActiveChannel(id: number) {
  return {
    type: 'home/set_active_channel',
    payload: id
  }
}

// 添加频道
export function addChannel(channel: Channel): RootThunkAction {
  return async (dispatch, getState) => {
    // 获取当前Redux中的‘我的频道’数据
    const { userChannels } = getState().home

    if (hasToken()) {
      await request.patch('/user/channels', { channels: [channel] })
    }
    // 如果未登录，则向本地缓存中保存新增的频道
    else {
      setChannels([...userChannels, channel])
    }

    dispatch({
      type: 'home/set_user_channels',
      payload: [...userChannels, channel]
    })
  }
}

// 删除我的频道
export function removeChannel(id: number): RootThunkAction {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home

    // 如果已登录，则调用后端接口来删除频道
    if (hasToken()) {
      await request.delete('/user/channels', {
        data: { channels: [id] }
      })
    }
    // 如果未登录，则删除本地缓存中的频道
    else {
      const filteredChannels = userChannels.filter((item) => item.id !== id)
      setChannels(filteredChannels)
    }

    // 重新获取 ”我的频道“ 数据
    dispatch(getUserChannel())
  }
}

// 获取文章列表
export function getArticleList(
  channel_id: number,
  timestamp: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<
      ApiRes<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        channel_id,
        timestamp
      }
    })

    const { pre_timestamp, results } = res.data.data

    dispatch({
      type: 'home/set_channel_articles',
      payload: {
        timestamp: pre_timestamp,
        channel_id,
        articles: results
      }
    })
  }
}

// 下拉刷新文章列表
export function getNewList(
  channel_id: number,
  timestamp: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<
      ApiRes<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        channel_id,
        timestamp
      }
    })

    const { pre_timestamp, results } = res.data.data

    dispatch({
      type: 'home/refresh_articles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results
      }
    })
  }
}
